<template>
    <div v-if="step == 'HOME'">
        <ConditionCard
            body-style="padding: 24px"
            class="groupList-addUser"
            @search="searchTable"
            @reset="reset"
        >
            <el-form ref="queryForm" :model="queryForm" label-width="80px" label-suffix="：">
                <el-row :gutter="2">
                    <el-col :span="8">
                        <el-form-item :label="$t('exchangeApproval.yearAndSemester')">
                            <CalendarSelect
                                v-model="queryForm.condition.calendarId"
                            ></CalendarSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('exchangeApproval.college')">
                            <DictSelect
                                :placeholder="$t('exchangeApproval.pleaseSelect')"
                                v-model="queryForm.condition.faculty"
                                :data="options.facultyList"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('exchangeApproval.studentNumber')">
                            <el-input
                                v-model="queryForm.condition.stuId"
                                style="width: 100%"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item :label="$t('exchangeApproval.fullName')">
                            <el-input
                                v-model="queryForm.condition.studentName"
                                style="width: 100%"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('exchangeApproval.auditStatus')">
                            <DictSelect
                                 :placeholder="$t('exchangeApproval.pleaseSelect')"
                                v-model="queryForm.condition.status"
                                :data="options.status"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card>
            <el-row type="flex" justify="space-between" align="center" style="margin-bottom:16px">
                <el-col :span="12">
                    <h1 slot="header">{{$t('exchangeApproval.applicationList')}}</h1>
                </el-col>
                <el-col :span="12" style="text-align:right">
                    <el-button v-if="global.currentUser.innerRoles.includes('2')" @click="handleClick('DR')">
                        {{$t('exchangeApproval.designatedReviewer')}}
                    </el-button>
                    <el-button v-if="global.currentUser.innerRoles.includes('2')" @click="handleClick('CD')">
                       {{$t('exchangeApproval.unassign')}}
                    </el-button>
                    <el-button
                        @click="handleClick('AB')"
                        v-if="global.currentUser.innerRoles.includes('2')"
                        type="primary"
                    >
                         {{$t('exchangeApproval.applyBehalf')}}
                    </el-button>
                    <el-button @click="handleClick('EX')" type="primary">{{$t('exchangeApproval.clickUpload')}}</el-button>
                </el-col>
            </el-row>
            <edu-table
                :data="tableList"
                :total="queryForm.total_"
                :pageSize="queryForm.pageSize_"
                @page-change="onCurrentPageChange"
                @selection-change="handleSelectionChange"
            >
                <el-table-column :label="$t('exchangeApproval.studentNumber')" prop="studentId" width="80"></el-table-column>
                <el-table-column
                   :label="$t('exchangeApproval.fullName')"
                    prop="studentName"
                    width="80"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                   :label="$t('exchangeApproval.yearAndSemester')"
                    prop="calendarName"
                    width="170"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.exchangeName')"
                    prop="exchangesName"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.schoolName')"
                    prop="exchangesUniversityNameZH"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.exchangesStartTime')"
                    prop="exchangesStartTime"
                    width="110"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.exchangesEndTime')"
                    prop="exchangesEndTime"
                    width="110"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('exchangeApproval.applicationDate')"
                    show-overflow-tooltip
                    width="155"
                    prop="createTime"
                ></el-table-column>
                <el-table-column :label="$t('exchangeApproval.reviewer')"  show-overflow-tooltip fixed="right" min-width="120">
                    <template slot-scope="scope">
                        <!-- <el-button
                            type="text"
                            v-if="scope.row.status == 1"
                            @click.stop="showUserGroup(scope.row.approver)"
                        >
                            {{ scope.row.approverName }}
                        </el-button>
                        <span v-else>{{ scope.row.approverName }}</span> -->
                        <el-button
                            type="text"
                            size="medium"
                            v-if="!scope.row.assignApprover"
                            @click.stop="showUserGroup(scope.row.approver)"
                        >
                            {{ scope.row.approverName }}
                        </el-button>
                        <span v-else>{{ scope.row.approverName }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('exchangeApproval.auditStatus')" fixed="right">
                    <template slot-scope="scope">
                        <el-tag :type="getStatus(scope.row.status)['type']">
                            {{ getStatus(scope.row.status)['label'] }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('exchangeApproval.operate')" fixed="right" width="150px">
                    <template slot-scope="scope">
                        <!-- 学生点击返校申请按钮或者管理员点击返校确认后，撤销按钮都隐藏 -->
                        <el-button
                            type="text"
                            v-if="scope.row.status == 3 && global.isAdmin && +scope.row.backType !== 3 && +scope.row.backType !== 2"
                            @click.stop="handleOperate('WITHDRAW', scope.row)"
                        >
                            {{$t('exchangeApproval.withdraw')}}
                        </el-button>
                        <el-button
                            type="text"
                            @click.stop="handleOperate('AUDIT', scope.row)"
                            v-if="!scope.row.isApproveShow"
                        >
                             {{$t('exchangeApproval.toExamine')}}
                        </el-button>
                        <el-button type="text" @click.stop="handleOperate('VIEW', scope.row)">
                              {{$t('exchangeApproval.check')}}
                        </el-button>
                        <el-button
                            type="text"
                            v-if="global.isAdmin && (+scope.row.backType === 2 || +scope.row.backType === 3)"
                            :disabled="+scope.row.backType === 3"
                            @click.stop="handleOperate('BACKCOM', scope.row)"
                        >
                             {{$t('exchangeApproval.returnToSchool')}}
                        </el-button>
                    </template>
                </el-table-column>
            </edu-table>
        </el-card>
        <el-dialog
            :title="$t('exchangeApproval.designatedReviewer')"
            :visible.sync="designReviewerDialog.visible"
            width="40%"
            :before-close="handleCloseDesignDialog"
        >
            <el-form
                label-suffix="："
                :model="designReviewerDialog"
                label-position="right"
                ref="designReviewerDialog"
                label-width="100px"
            >
                <el-form-item
                    prop="teacherValue"
                    :label="$t('exchangeApproval.teacher')"
                    :rules="[
                        {
                            required: true,
                            message: this.$t('exchangeApproval.pleaseEnterTeacher'),
                            trigger: ['blur', 'change']
                        }
                    ]"
                >
                    <el-autocomplete
                        style="width:90%"
                        v-model="designReviewerDialog.teacherValue"
                        :fetch-suggestions="querySearchAsync"
                        :placeholder="$t('exchangeApproval.pleaseEnterTeacherId')"
                        @select="handleSelect"
                    ></el-autocomplete>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleCloseDesignDialog">{{$t('exchangeApproval.cancel')}}</el-button>
                <el-button type="primary" @click="handleClick('DRS')">{{$t('exchangeApproval.determine')}}</el-button>
            </span>
        </el-dialog>
        <el-dialog v-drag-dialog title="组内用户明细" :visible.sync="userFormDialog.visiable">
            <edu-table
                :pageSize="userFormDialog.params.pageSize_"
                :total="userFormDialog.params.total_"
                :page-num="userFormDialog.params.pageNum_"
                @page-change="pageChangeDialog"
                :data="userFormDialog.userList"
                :selection="false"
            >
                <el-table-column label="账号">
                    <template slot-scope="scope">
                        {{ scope.row.studentId }}
                    </template>
                </el-table-column>
                <el-table-column label="用户名">
                    <template slot-scope="scope">
                        {{ scope.row.name }}
                    </template>
                </el-table-column>
                <el-table-column label="联系电话">
                    <template slot-scope="scope">
                        {{ scope.row.phoneNumber }}
                    </template>
                </el-table-column>
                <el-table-column label="联系邮箱" min-width="150">
                    <template slot-scope="scope">
                        {{ scope.row.email }}
                    </template>
                </el-table-column>
                <el-table-column label="类型">
                    <template slot-scope="scope">
                        {{
                            scope.row.userType == '1'
                                ? '老师'
                                : scope.row.userType == '2'
                                ? '学生'
                                : '本地用户'
                        }}
                    </template>
                </el-table-column>
            </edu-table>
        </el-dialog>
    </div>
    <div v-else>
        <el-row type="flex" justify="space-between">
            <el-col :span="12">
                {{$t('exchangeApproval.approvalAndAgent')}}
            </el-col>
            <el-col :span="12" style="text-align:right">
                <el-button type="text" @click="step = 'HOME'"> {{$t('exchangeApproval.back')}}</el-button>
            </el-col>
        </el-row>
        <el-card
            body-style="display: flex;
                        flex-direction: column;
                        align-items: center;"
        >
            <h2 slot="header"> {{$t('exchangeApproval.agencyApplication')}}</h2>
            <el-form
                label-suffix="："
                :model="behalfForm"
                label-position="right"
                ref="behalfForm"
                label-width="100px"
            >
                <el-form-item
                    :label="$t('exchangeApproval.studentNumber')"
                    prop="studentId"
                    :rules="[
                        {
                            required: true,
                            message: this.$t('exchangeApproval.pleaseSearchTeacherId'),
                            trigger: ['change', 'blur']
                        }
                    ]"
                >
                    <KeywordInput
                        v-model="behalfForm.studentId"
                        :placeholder="$t('exchangeApproval.pleaseEnterstudentId')"
                        @enter="queryStudentInfo"
                    />
                </el-form-item>
                <el-form-item  :label="$t('exchangeApproval.fullName')" prop="studentName">
                    <el-input
                        style="width:250px"
                        disabled
                        v-model="behalfForm.studentName"
                    ></el-input>
                </el-form-item>
                <el-form-item :label="$t('exchangeApproval.grade')" prop="grade">
                    <el-input style="width:250px" disabled v-model="behalfForm.grade"></el-input>
                </el-form-item>
                <el-form-item :label="$t('exchangeApproval.college')" prop="facultyI18n">
                    <el-input
                        style="width:250px"
                        disabled
                        v-model="behalfForm.facultyI18n"
                    ></el-input>
                </el-form-item>
                <el-form-item :label="$t('exchangeApproval.major')" prop="professionI18n">
                    <el-input
                        style="width:250px"
                        disabled
                        v-model="behalfForm.professionI18n"
                    ></el-input>
                </el-form-item>
                <el-form-item :label="$t('exchangeApproval.sex')" prop="sexI18n">
                    <el-input style="width:250px" disabled v-model="behalfForm.sexI18n"></el-input>
                </el-form-item>
                <el-form-item prop="canApply" style="display:none">
                    <el-switch v-model="behalfForm.canApply"></el-switch>
                </el-form-item>
            </el-form>
            <span>
                <el-button @click="handleClickBehalfForm('RESET')">{{$t('exchangeApproval.reset')}}</el-button>
                <el-button
                    :disabled="!behalfForm.canApply"
                    type="primary"
                    @click="handleClickBehalfForm('ADD')"
                >
                   {{$t('exchangeApproval.applyBehalf')}}
                </el-button>
            </span>
        </el-card>
        <el-dialog
            :title="$t('exchangeApproval.apply')"
            :visible.sync="dialog.visiable"
            :close-on-click-modal="false"
            @close="dialogClose"
            @open="dialogOpen"
            width="60%"
        >
            <el-form
                label-suffix="："
                :model="dialog.applyParams"
                label-position="right"
                ref="dialog"
                label-width="150px"
            >
                <h2> {{$t('exchangeApproval.essentialInformation')}}</h2>
                <el-row>
                    <el-col span="8">
                        <el-form-item :label="$t('exchangeApproval.fullName')">{{ behalfForm.studentName }}</el-form-item>
                    </el-col>
                    <el-col span="8">
                        <el-form-item :label="$t('exchangeApproval.studentNumber')">{{ behalfForm.studentId }}</el-form-item>
                    </el-col>
                    <el-col span="8">
                        <el-form-item :label="$t('exchangeApproval.college')">{{ behalfForm.facultyI18n }}</el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col span="8">
                        <el-form-item :label="$t('exchangeApproval.major')">
                            {{ behalfForm.professionI18n }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <h2>{{$t('exchangeApproval.exchangeDetails')}}</h2>
                <el-row>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.exchangeName')"
                            prop="exchangesName"
                            :rules="[
                                {
                                    required: true,
                                    message: this.$t('exchangeApproval.pleaseEnterExchangeName'),
                                    trigger: 'blur'
                                }
                            ]"
                        >
                            <el-input
                                v-model="dialog.applyParams.exchangesName"
                                :placeholder="$t('exchangeApproval.pleaseEnterExchangeName')"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.schoolName')"
                            prop="exchangesUniversity"
                            :rules="[{ required: true, message:this.$t('exchangeApproval.pleaseSelect'), trigger: 'change' }]"
                        >
                            <el-select
                                v-model="dialog.applyParams.exchangesUniversity"
                                :placeholder="$t('exchangeApproval.pleaseSelect')"
                                style="width:100%"
                                @change="unChange"
                            >
                                <el-option
                                    v-for="item in options.collegeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.exchangesCountry')"
                            prop="exchangesCountry"
                            :rules="[
                                { required: true, message: this.$t('exchangeApproval.pleaseEnterCountry'), trigger: 'blur' }
                            ]"
                        >
                            <el-input
                                v-model="dialog.applyParams.exchangesCountryI18n"
                                :placeholder="$t('exchangeApproval.pleaseEnterCountry')"
                                disabled
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.natureOfCommunication')"
                            prop="exchangesNature"
                            :rules="[{ required: true, message: this.$t('exchangeApproval.pleaseSelect'), trigger: 'change' }]"
                        >
                            <el-select
                                v-model="dialog.applyParams.exchangesNature"
                                :placeholder="$t('exchangeApproval.pleaseSelect')"
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.exchangesNatureList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.startTime')"
                            prop="exchangesStartTime"
                            :rules="[
                                {
                                    required: true,
                                    message: this.$t('exchangeApproval.pleaseEnterStartTime'),
                                    trigger: 'change'
                                }
                            ]"
                        >
                            <el-date-picker
                                type="date"
                                style="width:100%"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                :placeholder="$t('exchangeApproval.selectDate')"
                                v-model="dialog.applyParams.exchangesStartTime"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col span="12">
                        <el-form-item
                            :label="$t('exchangeApproval.endTime')"
                            prop="exchangesEndTime"
                            :rules="[
                                {
                                    required: true,
                                    message: this.$t('exchangeApproval.pleaseEnterEndTime'),
                                    trigger: 'change'
                                }
                            ]"
                        >
                            <el-date-picker
                                type="date"
                                style="width:100%"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                :placeholder="$t('exchangeApproval.selectDate')"
                                v-model="dialog.applyParams.exchangesEndTime"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="space-between">
                    <el-form-item
                        ref="exchangeCourseScheduleList"
                        :label="$t('exchangeApproval.exchangeSchedule')"
                        prop="attachmentCategoryDTO.exchangeCourseScheduleList"
                        :rules="[
                            {
                                required: true,
                                message: this.$t('exchangeApproval.pleaseUploadCourse'),
                                trigger: 'change'
                            }
                        ]"
                    >
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(
                                        response,
                                        file,
                                        fileList,
                                        'exchangeCourseScheduleList'
                                    )
                            "
                            :on-remove="
                                (file, fileList) =>
                                    handlerRemove(file, fileList, 'exchangeCourseScheduleList')
                            "
                            :before-upload="beforeUpload"
                            :on-error="handlerError"
                            :file-list="
                                dialog.applyParams.attachmentCategoryDTO.exchangeCourseScheduleList
                            "
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary">
                                    <i class="el-icon-upload el-icon--left"></i>
                                    {{$t('exchangeApproval.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip">
                                     {{$t('exchangeApproval.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-button type="primary" @click="download">{{$t('exchangeApproval.downloadCourse')}}</el-button>
                </el-row>
                <el-row type="flex" justify="space-between">
                    <el-form-item
                        :label="$t('exchangeApproval.schoolApproval')"
                        ref="schoolCertificateList"
                        prop="attachmentCategoryDTO.schoolCertificateList"
                        :rules="[
                            {
                                required: true,
                                message: this.$t('exchangeApproval.pleaseUploadApproval'),
                                trigger: 'change'
                            }
                        ]"
                    >
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(
                                        response,
                                        file,
                                        fileList,
                                        'schoolCertificateList'
                                    )
                            "
                            :on-remove="
                                (file, fileList) =>
                                    handlerRemove(file, fileList, 'schoolCertificateList')
                            "
                            :before-upload="beforeUpload"
                            :on-error="handlerError"
                            :file-list="
                                dialog.applyParams.attachmentCategoryDTO.schoolCertificateList
                            "
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary">
                                    <i class="el-icon-upload el-icon--left"></i>
                                    {{$t('exchangeApproval.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip">
                                    {{$t('exchangeApproval.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-button type="primary" style="display:none" @click="download">
                        {{$t('exchangeApproval.downloadCourse')}}
                    </el-button>
                </el-row>
                <el-row type="flex" justify="space-between">
                    <el-form-item :label="$t('exchangeApproval.other')">
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(response, file, fileList, 'otherAttachList')
                            "
                            :on-remove="
                                (file, fileList) => handlerRemove(file, fileList, 'otherAttachList')
                            "
                            :before-upload="beforeUpload"
                            :on-error="handlerError"
                            :file-list="dialog.applyParams.attachmentCategoryDTO.otherAttachList"
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary">
                                    <i class="el-icon-upload el-icon--left"></i>
                                    {{$t('exchangeApproval.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip">
                                     {{$t('exchangeApproval.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-button type="primary" style="display:none" @click="download">
                        {{$t('exchangeApproval.downloadCourse')}}
                    </el-button>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="danger" @click="dialog.visiable = false">{{$t('exchangeApproval.cancel')}}</el-button>
                <el-button type="primary" @click="handleClickDlg">{{$t('exchangeApproval.determine')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import UTILS from 'common/src/utils/utils'
import { queryDic } from 'common/src/api/dictionary'
import {
    applyList,
    downloadTemplate,
    addApply
} from 'common/src/api/internationalExchanges/exchangeApplication'
import {
    assign,
    cancel,
    recall,
    queryStuInfo,
    exportApplyList,
    recallPrivate,
    affirm
} from 'common/src/api/internationalExchanges/exchangeApproval'
import { getUserInfoListByGroupId } from 'common/src/api/user'
import SchoolCalendarApi from "common/src/api/calendars";
import { findTeacherInfoList } from 'common/src/api/studentinfo'
import { getUS } from 'common/src/api/internationalExchanges/exchangeCollegeManagement'
import mixin from 'common/src/mixins/index';
export default {
    mixins: [mixin],
    data() {
        return {
            step: 'HOME', //HOME:交流审批页面；BEHALF:待申请页
            queryForm: {
                total_: 0,
                pageNum_: 1,
                pageSize_: 20,
                condition: {
                    calendarId: '',
                    faculty: '',
                    stuId: '',
                    studentName: '',
                    status: '',
                    queryType: 1
                }
            },
            currentCalendarId: "",
            tableList: [],
            multipleSelection: [],
            behalfForm: {
                canApply: false,
                studentId: '',
                studentName: '',
                grade: '',
                faculty: '',
                facultyI18n: '',
                profession: '',
                professionI18n: '',
                sex: '',
                sexI18n: ''
            },
            userFormDialog: {
                visiable: false,
                userList: [],
                params: {
                    groupId: '',
                    userName: '',
                    pageNum_: 1,
                    total_: 0,
                    pageSize_: 20
                }
            },
            dialog: {
                visiable: false,
                mode: '',
                applyParams: {
                    id: '',
                    type: '1',
                    studentId: '',
                    studentName: '',
                    exchangesName: '',
                    exchangesUniversity: '',
                    exchangesCountry: '',
                    exchangesCountryI18n: '',
                    exchangesNature: '',
                    exchangesStartTime: '',
                    exchangesEndTime: '',
                    attachmentCategoryDTO: {
                        exchangeCourseScheduleList: [],
                        schoolCertificateList: [],
                        otherAttachList: []
                    }
                }
            },
            designReviewerDialog: {
                visible: false,
                teacherValue: '',
                teacherObj: {}
            },
            options: {
                facultyList: [],
                collegeList: [],
                exchangesNatureList: [],
                status: [
                    {
                        value: 0,
                        label: '草稿',
                        type: 'info'
                    },
                    {
                        value: 1,
                        label: '审核中',
                        type: ''
                    },
                    {
                        value: 2,
                        label: '已驳回',
                        type: 'warning'
                    },
                    {
                        value: 3,
                        label: '已通过',
                        type: 'success'
                    },
                    {
                        value: 4,
                        label: '已提交',
                        type: 'success'
                    }
                ]
            }
        }
    },
    mounted() {
        /*获取当前学期学年*/
        this.getCurrentTermCalendar().then(resp => {
            this.currentCalendarId = resp.data.schoolCalendar&&resp.data.schoolCalendar.id;
            this.queryForm.condition.calendarId = this.currentCalendarId;
        }).finally(()=>{
            this.queryTableList();
        })
        this.init()
    },
    methods: {
        init() {
            //筛选条件字典查询
            let data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_JLXZ', 'X_YX']
            }
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                        {
                            facultyList: 'X_YX',
                            exchangesNatureList: 'X_JLXZ'
                        },
                        res.data,
                        this.options
                    )
                }
            })
        },
        async queryCollegeList() {
            let params = {
                total_: 0,
                pageNum_: 1,
                pageSize_: 1000,
                condition: {}
            }
            let { code, data } = await getUS(params)
            if (code !== 200) return
            this.options.collegeList = data.list.map(item => {
                return {
                    label:
                        this.$store.getters.language == 'cn'
                            ? item.universityNameZN
                            : item.universityNameEN,
                    value: item.universityNameCode,
                    regionName:
                        this.$store.getters.language == 'cn'
                            ? item.regionNameZN
                            : item.regionNameEN,
                    regionCode: item.regionCode
                }
            })
        },
        getStatus(type = 0) {
            let list = this.options.status
            let obj = list.find(item => item.value == type)
            return obj
        },
        async getCurrentTermCalendar() {
            return await SchoolCalendarApi.currentTermCalendar();
        },
        searchTable() {
            this.queryForm.pageNum_ = 1;
            this.queryTableList();
        },
        async queryTableList(params = this.queryForm) {
            let { code, data } = await applyList(params)
            if (code !== 200) return
            this.tableList = data.list
            this.queryForm.total_ = data.total_
            this.queryForm.pageSize_ = data.pageSize_
        },
        onCurrentPageChange(pager) {
            this.queryForm.pageSize_ = pager.pageSize
            this.queryForm.pageNum_ = pager.pageNum
            this.queryTableList()
        },
        showUserGroup(groupId = '') {
            this.userFormDialog.params.groupId = groupId
            this.userFormDialog.visiable = !this.userFormDialog.visiable
            this.getUserInfoListByGroupId()
        },
        /**
         * params {groupId 用戶組ID}
         * 根据用户组iD 查询用户
         */
        async getUserInfoListByGroupId() {
            try {
                if (!this.userFormDialog.params.groupId) {
                    this.$message({
                        type: 'error',
                        message: '查询出错, 请重试.'
                    })
                    return
                }
                let { code, data } = await getUserInfoListByGroupId(this.userFormDialog.params)
                if (code == 200) {
                    this.userFormDialog.userList = data ? data.list : []
                    this.userFormDialog.params.total_ = data.total_
                    this.userFormDialog.params.pageNum_ = data.pageNum_
                    this.userFormDialog.params.pageSize_ = data.pageSize_
                }
            } catch (err) {
                this.$message({
                    type: 'error',
                    message: '查询出错, 请重试.'
                })
            }
        },
        pageChangeDialog(val) {
            this.userFormDialog.params.pageSize_ = val.pageSize
            this.userFormDialog.params.pageNum_ = val.pageNum
            this.getUserInfoListByGroupId()
        },
        async querySearchAsync(queryString, cb) {
            let result
            let params = { condition: queryString, pageNum_: 1, total: 0, pageSize_: 20 }
            let { code, data } = await findTeacherInfoList(params)
            result = data.list.map(item => {
                return {
                    auditorName: item.name,
                    auditorId: item.code,
                    value: `${item.name}(${item.code})${item.facultyI18n}`
                }
            })
            cb(result)
        },
        handleCloseDesignDialog() {
            this.designReviewerDialog.visible = false
            this.designReviewerDialog.teacherValue = ''
            this.designReviewerDialog.teacherObj = {}
            this.$refs['designReviewerDialog'] && this.$refs['designReviewerDialog'].resetFields()
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        handleSelect(item) {
            this.designReviewerDialog.teacherObj = item
        },
        checkStatus(status, list) {
            return list.every(item => item.status == status)
        },
        handleClick(mode) {
            let len = this.multipleSelection.length
            switch (mode) {
                //指定审核人
                case 'DR':
                    if (!len) {
                        this.$message({
                            type: 'warning',
                            message: '请先选择需要指定审核人的列表记录'
                        })
                        return
                    }
                    if (!this.checkStatus(4, this.multipleSelection)) {
                        this.$message({
                            type: 'warning',
                            message: '只有已提交状态的列表才能进行此操作'
                        })
                        return
                    }
                    this.designReviewerDialog.visible = !this.designReviewerDialog.visible
                    break
                //指定审核人提交
                case 'DRS':
                    this.$refs['designReviewerDialog'].validate(valid => {
                        if (valid) {
                            let obj = this.designReviewerDialog.teacherObj
                            let ids = this.multipleSelection.map(item => item.id)
                            let list = this.multipleSelection.map(item => item.workflowNo)
                            let params = {
                                type: '1',
                                ids: ids,
                                auditorId: obj.auditorId,
                                auditorName: obj.auditorName,
                                workflowNo: list
                            }
                            this.designReviewer(mode, params)
                        } else {
                            return false
                        }
                    })
                    break
                //取消指定
                case 'CD':
                    if (!len) {
                        this.$message({
                            type: 'warning',
                            message: '请先选择需要取消指定审核人的列表记录'
                        })
                        return
                    }
                    if (!this.checkStatus(4, this.multipleSelection)) {
                        this.$message({
                            type: 'warning',
                            message: '只有已提交状态的列表才能进行此操作'
                        })
                        return
                    }
                    this.$confirm('此操作将取消所选列表指定审核人, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                        .then(() => {
                            let params = {
                                type: '1',
                                ids: this.multipleSelection.map(item => item.id),
                                auditorIdList: this.multipleSelection.map(item => item.approver),
                                workflowNo: this.multipleSelection.map(item => item.workflowNo)
                            }
                            this.designReviewer(mode, params)
                        })
                        .catch(() => {})

                    break
                //代申请
                case 'AB':
                    this.step = 'BEHALF'
                    break
                //导出
                case 'EX':
                    let params = _.cloneDeep(this.queryForm.condition)
                    delete params.queryType
                    Object.assign(params, {
                        exportType: 0,
                        ids: this.multipleSelection.map(item => item.id)
                    })
                    exportApplyList(params)
                    break
            }
        },
        handleClickBehalfForm(mode) {
            switch (mode) {
                case 'ADD':
                    this.$refs['behalfForm'].validate(valid => {
                        if (valid) {
                            this.dialog.visiable = !this.dialog.visiable
                            !this.options.exchangesNatureList.length && this.init()
                            !this.options.collegeList.length && this.queryCollegeList()
                        } else {
                            return false
                        }
                    })
                    break
                case 'RESET':
                    this.$refs['behalfForm'] && this.$refs['behalfForm'].resetFields()
                    break
            }
        },
        handleOperate(mode, data) {
            switch (mode) {
                //撤回
                case 'WITHDRAW':
                    this.$confirm('此操作将撤回此条审核记录, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                        .then(() => {
                            let request
                            let params = {}
                            if (data.workflowNo && !data.agencyWorkflowNo) {
                                request = recall
                                params = { no: data.workflowNo, content: '撤回' }
                            } else {
                                request = recallPrivate
                                params = { agencyWorkflowNo: data.agencyWorkflowNo, id: data.id }
                            }
                            request(params).then(res => {
                                if (res.code == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: '撤回成功'
                                    })
                                    this.reset()
                                }
                            })
                        })
                        .catch(() => {})
                    break
                //审核、查看
                case 'AUDIT':
                case 'VIEW':
                    this.$router.push({
                        name: 'UGIEApprovalDetail',
                        params: {
                            data,
                            mode
                        }
                    })
                    break
                case 'BACKCOM':
                    let _this = this
                    _this
                        .$confirm('是否继续返校确认?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        })
                        .then(() => {
                            affirm(data.id).then((res)=>{
                                if(res.code ==200){
                                    res.msg && this.$message({
                                        type: 'success',
                                        message: res.msg
                                    })
                                 _this.queryTableList()
                                }
                            })
                        })
            }
        },
        unChange(val) {
            let obj = this.options.collegeList.find(item => item.value == val)
            this.dialog.applyParams.exchangesCountryI18n = obj ? obj.regionName : ''
            this.dialog.applyParams.exchangesCountry = obj ? obj.regionCode : ''
        },
        async queryStudentInfo(id) {
            let { code, data, msg } = await queryStuInfo({
                studentId: id,
                isIllegal: true,
                isCurrentFaculty: true,
                isUndergraduate: true
            })
            if (code !== 200) return
            for (let key in this.behalfForm) {
                if (key !== 'canApply') {
                    this.behalfForm[key] = data ? data[key] : ''
                }
            }
            if (data) {
                this.dialog.applyParams.studentId = data['studentId']
                this.dialog.applyParams.studentName = data['studentName']
                this.behalfForm.canApply = !!data
            } else {
                this.behalfForm.canApply = !!data
                this.$eduAlert(msg)
            }
        },
        async designReviewer(mode, params) {
            let request = mode == 'DRS' ? assign(params) : cancel(params)
            let { code, data } = await request
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: mode == 'DRS' ? '指定审核人成功' : '取消指定审核人成功'
            })
            this.handleCloseDesignDialog()
            this.reset()
        },
        reset() {
            let condition = this.queryForm.condition
            for (let key in condition) {
                switch (key) {
                    case 'faculty':
                    case 'studentId':
                    case 'studentName':
                    case 'status':
                        condition[key] = ''
                        break
                }
            }
            this.queryForm.total_ = 0
            this.queryForm.pageNum_ = 1
            this.queryForm.pageSize_ = 20
            this.queryTableList()
        },
        //移除文件回调
        handlerRemove(file, fileList, mode) {
            let list = this.dialog.applyParams.attachmentCategoryDTO[mode]
            let index = list.findIndex(item => item.uid == file.uid)
            list.splice(index, 1)
            this.dialog.applyParams.attachmentCategoryDTO[mode] = list
        },
        //上传文件成功回调
        handlerSuccess(response, file, fileList, mode) {
            let responseCode = response.code
            let type
            if (mode == 'exchangeCourseScheduleList') {
                type = 1
            } else if (mode == 'schoolCertificateList') {
                type = 2
            } else {
                type = 3
            }
            if (responseCode === 200) {
                this.dialog.applyParams.attachmentCategoryDTO[mode].push({
                    type: type,
                    name: file && file.name,
                    url: file.response.data[file.name] && file.response.data[file.name].objectkey
                })
                let len = this.dialog.applyParams.attachmentCategoryDTO[mode]
                if (len.length > 0) this.$refs[mode].clearValidate()
            } else {
                this.$message({
                    message: '文件列名错误或文件为空！',
                    type: 'error'
                })
            }
        },
        //上传文件失败回调
        handlerError(response, file, fileList) {
            this.$message({
                message: '上传失败！',
                type: 'error'
            })
        },
        //上传文件类型校验
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.doc,.docx,.xls,.xlsx,.jpg,.bmp,.png,.pdf',
                    size: '5'
                },
                this
            )
        },
        download() {
            //课程计划表模板下载
            downloadTemplate()
        },
        async submit() {
            let { code, data } = await addApply(this.dialog.applyParams)
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: '代申请成功'
            })
            this.dialog.visiable = !this.dialog.visiable
            this.queryTableList()
            this.step = 'HOME'
        },
        handleClickDlg() {
            this.$refs['dialog'].validate(valid => {
                if (valid) {
                    this.submit()
                } else {
                    return false
                }
            })
        },
        dialogClose() {
            this.dialog.mode = ''
            for (let key in this.dialog.applyParams) {
                if (
                    key !== 'attachmentCategoryDTO' &&
                    key !== 'type' &&
                    key !== 'studentId' &&
                    key !== 'studentName'
                ) {
                    this.dialog.applyParams[key] = ''
                }
            }
            for (let key in this.dialog.applyParams.attachmentCategoryDTO) {
                this.dialog.applyParams.attachmentCategoryDTO[key] = []
            }
        },
        dialogOpen() {
            this.$refs['dialog'] && this.$refs['dialog'].clearValidate()
        }
    }
}
</script>
<style lang="scss" scoped>
</style>
